//
//  YZMHomePageViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/23.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMHomePageViewController.h"
#import "YZMSegmentViewScroll.h"
#import "YZMAlertView.h"
#import "YZMWebViewService.h"
#import "NSNumber+Utils.h"
#import "MBProgressHUD+Utils.h"
#import "JSONBaseDeal.h"

#import "YZClient.h"
#import "YZMPageControl.h"
#import "YZMConfigureService.h"

#import <NSArray+LinqExtensions.h>
#import <NSDictionary+LinqExtensions.h>
#import <DateTools/DateTools.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import <ColorUtils/ColorUtils.h>
#import "YZMStockRealModel.h"
#import <NSDate+DateTools.h>
#import "YZMPatchManager.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "YZMHomeBannerModel.h"
#import <MJRefresh/MJRefreshNormalHeader.h>
#import <UIButton+WebCache.h>
#import "YZMyStocksTopCell.h"
#import "YZMStockInfo.h"
#import "YZMSegmentViewScroll.h"
#import "YZMTradeCell.h"
#import "YZMMasterCell.h"
#import "YZMHomeRankModel.h"
#import "YZMHomeStrategyModel.h"
#import "YZMHomeUsersModel.h"
#import "YZMTrendCell.h"
#import "YZMRankCell.h"
#import "YZMHomeTrendModel.h"
#import "YZMHomeRankListModel.h"
#import "YZMBundleVersionControlService.h"
#import "YZMHomeOptionStockView.h"
//#import "YZMHomePageSectionView.h"
#import "YZMHomePageSectionView2.h"
#import "YZMHomePageCell.h"
#import "YZDKnowledgeViewController.h"
#import "YZMInfoViewController.h"
#import "YZMFreeExperienceViewController.h"
#import "YZMCheckService.h"
#import "YZClient+Activity.h"
#import "YZMActivityModel.h"

#define YZMCHECKSERVICE [YZMCheckService sharedService]


#define sYZMLastUpdateTimeDefault  @"YZMLastUpdateTimeDefault"

#define HOME_PAGE_TAG_FOR_STOCK  1000
#define HOME_PAGE_TAG_FOR_HSI           HOME_PAGE_TAG_FOR_STOCK + 1
#define HOME_PAGE_TAG_FOR_GC            HOME_PAGE_TAG_FOR_HSI + 1
#define HOME_PAGE_TAG_FOR_CL            HOME_PAGE_TAG_FOR_GC + 1
#define HOME_PAGE_TAG_FOR_HSI_SIMULATE  HOME_PAGE_TAG_FOR_CL + 1
#define HOME_PAGE_TAG_FOR_GC_SIMULATE   HOME_PAGE_TAG_FOR_HSI_SIMULATE + 1
#define HOME_PAGE_TAG_FOR_CL_SIMULATE   HOME_PAGE_TAG_FOR_GC_SIMULATE + 1

#define TOP_CELL_ROWHEIGHT   100
#define kMainWidth [UIScreen mainScreen].bounds.size.width

#define NavigationBarHeight  (NSInteger)(iPhoneX ? 88 : 64)
#define TabBarHeight  (NSInteger)(iPhoneX ? 83 : 49)


static NSString *const home_page_stock_cell_identifier = @"YZMyStocksTopCell";
static NSString *const home_page_trade_cell_identifier = @"YZMRankCell";
static NSString *const home_page_master_cell_identifier = @"YZMTrendCell";
static NSString *const home_page_section_identifier = @"YZMHomePageSectionView";
static NSString *const home_page_review_cell_identifier = @"YZMHomePageCell";

@interface YZMHomePageViewController()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, SDCycleScrollViewDelegate,YZMHomePageSectionView2Delegate>

@property (nonatomic, strong) YZMHomeOptionStockView *optionStockView;

@property (nonatomic, strong) YZMHomePageSectionView2 *viewSection;

@property (nonatomic, strong) UIImageView *imageViewNew;

@property (nonatomic, strong) UIImageView *imageViewRedEnvelope;

@property (nonatomic, strong) NSMutableArray *arrActivity;

@end

@implementation YZMHomePageViewController
{
    NSMutableArray *_bannerData;
    NSString *_downloadUrl;

    UITableView *_stockClassTV;
    NSTimer *_stockTimer;
    NSTimer *_rankTimer;
    NSMutableDictionary *_realDataDict;
    NSString *_futuresStr;
    NSMutableArray *_item;
    BOOL _unShowErrorFlag;
    
    BOOL _networkReadyFlag;//网络检测完成标志
    BOOL _unFirstFetchAStockFlag;//非首次获取
    
    NSTimer *_bannerTimer;
    BOOL _unNeedCheckVersionFlag;//版本更新
    SDCycleScrollView *_cycleScrollview;
    NSArray *_bannerArr;
    NSArray *_adArr;
    NSArray *_lastAdArr;
    NSMutableArray *_imageUrlArr;
    MJRefreshNormalHeader *_refreshHeader;
    YZMSegmentViewScroll *_segView;
    UITableView *_tradeTV;
    UITableView *_masterTV;
    NSMutableArray *_rankStrategyArray;
    NSMutableArray *_rankUserArray;
    MBProgressHUD *_hud;
    UIImageView *oneYuanIntroduceImageView;
    NSMutableArray *_arrDataReview;
}

- (id)init{
    
    self = [super init];
    
    if (self) {
        self.title = @"首页";
//        self.navigationItem.title = @"微策略";
        //获取info.plist文件内容
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        self.navigationItem.title = infoDic[@"CFBundleDisplayName"];
        _bannerData = [NSMutableArray array];
        _imageUrlArr = [NSMutableArray array];
        _arrActivity = [NSMutableArray array];
        
        _realDataDict = [NSMutableDictionary dictionaryWithCapacity:1];
        _item = [NSMutableArray array];
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    if (YZMSWitchOn) {
        self.navigationItem.leftBarButtonItem = [YZMAppStyle leftBarItemWithImage:@"customer_service" target:self action:@selector(leftBarItemPressed:)];
        self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"icon_guide" target: self action: @selector(rightBarItemPressed:)];
    }
    [self createObjects];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
                                                 name:AFNetworkingReachabilityDidChangeNotification object:nil];
    
    _rankStrategyArray=[NSMutableArray array];
    _rankUserArray=[NSMutableArray array];
    if (!YZMSWitchOn) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"trade" ofType:@"json"];
        NSData *data = [[NSData alloc] initWithContentsOfFile:path];
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _arrDataReview = [NSMutableArray array];
        for (NSInteger i = 0; i < 4; i++) {
            [_arrDataReview addObject:arr[i]];
        }
    }
    [self fetchActivityList:nil];
}



#pragma mark -- init


- (void)reachabilityChanged:(NSNotification *)note{
    
    if (!_networkReadyFlag) {
        
        _networkReadyFlag = YES;
        [self checkUpdate];
        
        if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
            
            if (![[YZMConfigureService sharedService] isInTradeTimePeriods]) {
                
                [self fetchTrendListData];
            }
            [self fetchRankListData];
            [self startTimer];
            
        }
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
//    [_cycleScrollview adjustWhenControllerViewWillAppera];
    if (_networkReadyFlag || !kNetworkNotReachability) {
        
        _networkReadyFlag = YES;
        
        if (![[YZMConfigureService sharedService] isInTradeTimePeriods]) {
            
            [self fetchTrendListData];
        }
        [self fetchRankListData];
        [self startTimer];
        
    }
    [self.tabBarController.tabBar setNeedsUpdateConstraints];
    [self.tabBarController.tabBarController updateViewConstraints];
    [self checkUpdate];
}



- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self stopTimer];
}

#pragma mark -- timer

- (void)startTimer{
    
    if (_networkReadyFlag) {
        
        if (!_stockTimer) {
            
            _stockTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(fetchStockDetailInfo) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer: _stockTimer forMode: NSRunLoopCommonModes];
            [_stockTimer fire];
        }
        
        if (!_rankTimer) {
            _rankTimer=[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(fetchHomeTrendListData) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:_rankTimer forMode:NSRunLoopCommonModes];
            [_rankTimer fire];
        }

        //banner
        [self fetchHomeBannerListWithErrorShowFlag];
    }
}

- (void)stopTimer{
    
    if (_stockTimer) {
        
        if ([_stockTimer isValid]) {
            [_stockTimer invalidate];
        }
        _stockTimer = nil;
    }
        if (_rankTimer) {
            
            if ([_rankTimer isValid]) {
                [_rankTimer invalidate];
            }
            _rankTimer = nil;
    }

}


#pragma mark -- versionCheck

- (void)updateLogicDeal:(NSDictionary *)responseDic{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *buildVersion = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    if ([buildVersion integerValue] >= [JSONBaseDeal getIntValue:@"buildVersion" fromData:responseDic]) {
        
        return;
    }
    
    BOOL foreUpdateFlag = [JSONBaseDeal getIntValue:@"forceUpdate" fromData:responseDic]==1 ?YES:NO;
    
    _downloadUrl = [JSONBaseDeal getValue:@"downloadUrl" fromData:responseDic];
    
    if (foreUpdateFlag) {
        
        YZMAlertView *alertView = [YZMAlertView new];
        alertView.titleLabel.text = @"发现新版本";
        alertView.contentLabel.text = [JSONBaseDeal getValue:@"description" fromData:responseDic];
        alertView.cancelButton.hidden = YES;
        alertView.confirmHandle = ^(){
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downloadUrl]];
            return NO;
        };
        
        [alertView showInView:YZMCMInstance.rootTabBarCtrl.view];
        return;
    }
    
    NSInteger lastUpdateDateInteger = 0;
    
    NSDate *lastUpdateDate = [[NSUserDefaults standardUserDefaults] objectForKey:sYZMLastUpdateTimeDefault];
    
    if (lastUpdateDate) {
        
        lastUpdateDateInteger = [[lastUpdateDate formattedDateWithFormat:@"yyyyMMdd"] integerValue];
    }
    
    if (lastUpdateDateInteger != 0) {
        
        NSInteger nowDateInteger = [[[NSDate date] formattedDateWithFormat:@"yyyyMMdd"] integerValue];
        
        if (nowDateInteger <= lastUpdateDateInteger) {
            
            return;
        }
    }
    
    YZMAlertView *alertView = [YZMAlertView new];
    alertView.titleLabel.text = @"发现新版本";
    alertView.contentLabel.text = [JSONBaseDeal getValue:@"description" fromData:responseDic];
    [alertView.sureButton setTitle:@"立即更新" forState:UIControlStateNormal];
    alertView.confirmHandle = ^(){
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downloadUrl]];
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:sYZMLastUpdateTimeDefault];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    };
    alertView.cancleHandle = ^{
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:sYZMLastUpdateTimeDefault];
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    
    [alertView showInView:YZMCMInstance.rootTabBarCtrl.view];
}


- (void)checkUpdate{
    
    if (_unNeedCheckVersionFlag) {
        
        return;
    }
    
    _unNeedCheckVersionFlag = YES;
    [YZClient checkSoftwareUpdateSuccess:^(NSURLResponse *response, id responseObject){
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [self updateLogicDeal:topModel.data];
        }else{
            
            _unNeedCheckVersionFlag = NO;
        }
        
    } failure:^(NSError *error) {
        
        _unNeedCheckVersionFlag = NO;
    }];
}

#pragma mark - YZMHomePageSectionView2Delegate

- (void)pushVc{
    YZMInfoViewController *vc = [[YZMInfoViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [YZMHCMInstance pushViewController:vc animated:YES];
//    [YZMHCMInstance pushViewControllerWithName:NSStringFromClass([YZMInfoViewController class]) andParams:nil];
}

#pragma mark TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == _stockClassTV) {
        if (!YZMSWitchOn) {
            return 2;
        }
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _stockClassTV) {
        if (section == 0) {
            return 1;
        }else{
            if (!YZMSWitchOn) {
                return _arrDataReview.count;
            }
        }
        return 0;
    } else  if(tableView==_tradeTV){
        return _rankUserArray.count;
    }else if (tableView==_masterTV){
        
        return _rankStrategyArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _stockClassTV) {
        if (indexPath.section == 0) {
            YZMyStocksTopCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_stock_cell_identifier forIndexPath:indexPath];
            cell.leftRecord = _realDataDict[@"SH000001"];
            cell.middleRecord = _realDataDict[@"SZ399001"];
            cell.rightRecord = _realDataDict[@"SZ399006"];
            return cell;
        }else{
            if (!YZMSWitchOn) {
                YZMHomePageCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_review_cell_identifier forIndexPath:indexPath];
                NSDictionary *dic  = _arrDataReview[indexPath.row];
                [cell configCellWithDic:dic];
                return cell;
            }
        }
        return nil;
    } else if (tableView == _tradeTV) {
        
        YZMRankCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_trade_cell_identifier forIndexPath:indexPath];
        
        YZMHomeRankListModel *rankModel = _rankUserArray[indexPath.row];
        cell.rankModel = rankModel;
        cell.indexForImgageView = indexPath.row;
        
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row;
        indexCount.count = _rankUserArray.count;
        cell.indexCount = indexCount;
        
        return cell;
    } else if (tableView == _masterTV) {
        
        YZMTrendCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_master_cell_identifier forIndexPath:indexPath];
        WS(ws)
        cell.handle = ^{
            [ws tradeWith:indexPath];
        };
        cell.numberForColor = indexPath.row;
        
        YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
        cell.trendModel = trendModel;
        
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row;
        indexCount.count = _rankStrategyArray.count;
        cell.indexCount = indexCount;
        
        return cell;
    }
    
    return [[UITableViewCell alloc] init];
}

- (void)tradeWith:(NSIndexPath *)indexPath{
    if (indexPath.row<_rankStrategyArray.count) {
        YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
        if (trendModel.stockCode.length == 0) {
            return;
        }
        NSDictionary *param = nil;
        if (trendModel.stockName.length == 0) {
            param= @{@"stockcode":trendModel.stockCode};
        }else{
            param = @{@"stockcode":trendModel.stockCode,@"stockname":trendModel.stockName};
        }
        [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
    }
}

#pragma mark -- UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == _stockClassTV) {
        if (section != 0) {
            if (!YZMSWitchOn) {
                return self.viewSection;
            }
        }
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _stockClassTV) {
        
        return TOP_CELL_ROWHEIGHT;
    } else if(tableView == _masterTV){
        
        return 60;
    }else{
        
        return 48;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (tableView == _stockClassTV) {
        if (section == 0) {
            return 14;
        }
        return 44;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 14;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!YZMSWitchOn) {
        NSDictionary *dic = _arrDataReview[indexPath.row];
        [YZMHCMInstance pushViewControllerWithName:NSStringFromClass([YZDKnowledgeViewController class]) andParams:dic];
    }
    if (tableView == _masterTV) {
        if (indexPath.row<_rankStrategyArray.count) {
            YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
            if (trendModel.stockCode.length == 0) {
                return;
            }
            NSDictionary *param = nil;
            if (trendModel.stockName.length == 0) {
                param= @{@"stockcode":trendModel.stockCode};
            }else{
                param = @{@"stockcode":trendModel.stockCode,@"stockname":trendModel.stockName};
            }
            [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
        }
    }
}

#pragma mark -- NetWork Response

- (void)fetchHomeBannerListWithErrorShowFlag {
    if ([self checkNetwork]) {
        _unFirstFetchAStockFlag=YES;
        return;
    }
    if (!YZMSWitchOn) {
        return;
    }
    
    [YZClient fetchHomeBannerListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [self endRefresh];
            
            NSArray *bannerList = topModel.data;
            if (bannerList.count > 0) { //判断banner的个数是否大于0
                
                [_bannerData removeAllObjects];     //删除前次请求的banner内容
                [_bannerData addObjectsFromArray:bannerList];

                _bannerArr = [YZMHomeBannerModel mapResponseArray:_bannerData type:1];
                if (_bannerArr.count > 0) {
                    
                    //刷新banner数据
                    [self refreshBannerListView];
                }
                
                _adArr = [YZMHomeBannerModel mapResponseArray:_bannerData type:0];
                _lastAdArr = [YZMHomeBannerModel createDecoder];
                if (_adArr.count > 0 && ![_lastAdArr isEqualToArray:_adArr]) {
                    
                    //将广告Data保存到本地，判断是否下次启动显示
                    [YZMHomeBannerModel createEncoder:_adArr];
                    //显示广告图
                    [self showAdView];
                }
            }
        }
        
        _unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        
        [self endRefresh];
        
        if (!_unShowErrorFlag) {
            
            if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
                
                [error yz_showMessage];
            }
        }
        _unShowErrorFlag = YES;
    }];
}

-(void)fetchHomeTrendListData{
    
    if ([[YZMConfigureService sharedService] isInTradeTimePeriods]) {
        
        [self fetchTrendListData];
    }else{
        
        [_masterTV reloadData];
    }
}

-(void)fetchTrendListData{
    
    if ([self checkNetwork]) {
        _unFirstFetchAStockFlag=YES;
        [_hud hide:YES];
        return;
    }
    
    [YZClient fetchHomeTrendListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        [_hud hide:YES];
        if (topModel.success) {
            YZMHomeTrendModel *model = topModel.data;
            [_rankStrategyArray removeAllObjects];
            [_rankStrategyArray addObjectsFromArray:(NSArray *)model];
            [self tableset];
            [_masterTV reloadData];
        }
        _unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        [_hud hide:YES];
        if (!_unShowErrorFlag) {
            
            [error yz_showMessage];
        }
        _unShowErrorFlag = YES;
    }];
}

-(void)fetchRankListData{
    
    if ([self checkNetwork]) {
        _unFirstFetchAStockFlag=YES;
        [_hud hide:YES];
        return;
    }
    
    if (YZMSWitchOn) {
        [YZClient fetchHomeRankListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
            YZGeneralResultModel *topModel = responseObject;
            [_hud hide:YES];
            if (topModel.success) {
                YZMHomeRankListModel *model = topModel.data;
                [_rankUserArray removeAllObjects];
                [_rankUserArray addObjectsFromArray:(NSArray *)model];
                [self tableset];
                [_tradeTV reloadData];
            }
            _unShowErrorFlag = NO;
        } failure:^(NSError *error) {
            [_hud hide:YES];
            if (!_unShowErrorFlag) {
                
                [error yz_showMessage];
            }
            _unShowErrorFlag = YES;
        }];
    }else{
        
    }
}

//活动列表
- (void)fetchActivityList:(dispatch_group_t)group{
    
    WS(ws)
    [YZClient Activity_activityListsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel =responseObject;
        if (topModel.success) {
            [ws.arrActivity removeAllObjects];
            [ws.arrActivity addObjectsFromArray:topModel.data];
        }else{
            
            [topModel showMessage];
        }
        if (group) {
            dispatch_group_leave(group);
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
        if (group) {
            dispatch_group_leave(group);
        }
    }];
}


-(void)tableset
{
    [_tradeTV mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(48 * _rankUserArray.count);
    }];
    
    [_masterTV mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(60 * _rankStrategyArray.count);
    }];
}


- (void)fetchStockDetailInfo{
    
//    if ([self checkNetwork]) {
//        _unFirstFetchAStockFlag=YES;
//        return;
//    }
    
    NSMutableArray *array = [NSMutableArray array];
    
    [array addObject:@"SH000001"];
    [array addObject:@"SZ399001"];
    [array addObject:@"SZ399006"];
    
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        
        if ([_refreshHeader isRefreshing]) {
            
            [_refreshHeader endRefreshing];
        }
        YZGeneralResultModel *topModel = responseObject;
        if(topModel.success){
            [_realDataDict removeAllObjects];
            [_realDataDict addEntriesFromDictionary:topModel.data];
            [_stockClassTV reloadData];
            _unShowErrorFlag = NO;
        }else{
            if (!_unShowErrorFlag) {
                [topModel showMessage];
            }
            _unShowErrorFlag=YES;
        }
    } failure:^(NSError *error) {
        
        if (!_unShowErrorFlag) {
            
            if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
                
                [error yz_showMessage];
            }
        }
        _unShowErrorFlag = YES;
    }];
}


#pragma mark -- Event Response

-(void)newButtonAction:(UIButton *)sender{

    switch (sender.tag) {
        case 101:{
//            [YZMWebViewService openOneYuan];
          BOOL isClicked =  [[NSUserDefaults standardUserDefaults] boolForKey:@"clikedFreeEx"];
          if (!isClicked) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"clikedFreeEx"];
              _imageViewNew.hidden = YES;
            }
            [YZMWebViewService openFreeExperience];
//            YZMFreeExperienceViewController *freeVc = [[YZMFreeExperienceViewController alloc]init];
//               [YZMCHECKSERVICE checkForFreeExpericence];
//            [YZMHCMInstance pushViewController:freeVc animated:YES];
        }
            break;
            
        case 102:
            [YZMWebViewService openSimulate];
            break;
            
        default:
            break;
    }
}

-(void)firstButtonAction
{
    [YZMHCMInstance pushViewControllerWithName:@"stock" andParams:nil];
}

-(void)secondButtonAction
{
    [YZMHCMInstance pushViewControllerWithName:@"stockTD" andParams:nil];
}

- (void)leftBarItemPressed:(UIButton *)sender{
    
    [YZMWebViewService openSuggestionCenter];
}

- (void)rightBarItemPressed:(UIButton *)sender{
    
    [YZMWebViewService openGuide];
}

- (void)hideAdBtn {
    
    UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
    UIButton *shadowBtn = [currentWindow viewWithTag:120];
    UIButton *adBtn = [currentWindow viewWithTag:130];
    UIButton *closeBtn = [currentWindow viewWithTag:140];
    //加动画效果
    [UIView animateWithDuration:0.3 animations:^{
        
        adBtn.alpha = 0;
    } completion:^(BOOL finished) {
        
        [adBtn removeFromSuperview];
        [closeBtn removeFromSuperview];
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        shadowBtn.alpha = 0;
    } completion:^(BOOL finished) {
        
        [shadowBtn removeFromSuperview];
    }];
}

- (void)adToNextPage:(UIButton *)send {
    
    [self hideAdBtn];
    [self bannerOrAdClick:[_adArr lastObject]];
}

#pragma mark -- SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    NSDictionary *dic = _bannerArr[index];
    [self bannerOrAdClick:dic];
}

#pragma mark -- Private Method

- (void)bannerOrAdClick:(NSDictionary *)contentDic {
    
    NSDictionary *dic = contentDic[@"bannerEvent"];
    if ([dic[@"event"] isEqualToString:@""] && [dic[@"url"] isEqualToString:@""]) {
        
        return;
    }
    
    [YZMHomeBannerModel selectDirection:contentDic withLocal:YES];
}

- (void)showAdView {
    
    //取得keyWindow
    UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
    //创建阴影按钮
    UIButton *shadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shadowBtn.alpha = 0.6;
    shadowBtn.adjustsImageWhenHighlighted = NO;
    [shadowBtn setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle colorForBlackText]] forState:UIControlStateNormal];
    shadowBtn.tag = 120;
    [shadowBtn addTarget:self action:@selector(hideAdBtn) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:shadowBtn];
    [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(currentWindow);
    }];
    
    //创建广告弹窗
    UIButton *adBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    adBtn.backgroundColor = [UIColor clearColor];
    adBtn.tag = 130;
    adBtn.adjustsImageWhenHighlighted = NO;
    NSDictionary *dic = [_adArr lastObject];
    NSURL *url = [NSURL URLWithString:[dic[@"imageUrl"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];   //将下载地址转换为UTF8
    [adBtn sd_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:nil options:SDWebImageCacheMemoryOnly];
    [adBtn addTarget:self action:@selector(adToNextPage:) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:adBtn];
    [adBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(shadowBtn);
        make.width.mas_equalTo(ceil(ScreenWidth * 0.7));
        make.height.mas_equalTo(ceil(ScreenWidth * 0.7 / 0.8));
    }];
    
    //关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.backgroundColor = [UIColor clearColor];
    closeBtn.tag = 140;
    closeBtn.adjustsImageWhenHighlighted = NO;
    [closeBtn addTarget:self action:@selector(hideAdBtn) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.right.equalTo(adBtn);
        make.width.height.mas_equalTo(ceil(ScreenWidth * 0.7 * 0.2));
    }];
}

- (void)endRefresh {
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
}

- (void)downRefresh {
    //刷新banner中的数据
    [self fetchHomeBannerListWithErrorShowFlag];
    [self fetchStockDetailInfo];
}

- (void)refreshBannerListView {
    
    if (_bannerArr.count > 0) {
        
        [_imageUrlArr removeAllObjects];
        
        for (NSMutableDictionary *dic in _bannerArr) {
            
            //取得banner的下载地址List
            [_imageUrlArr addObject:dic[@"imageUrl"]];
        }
        
        if (_imageUrlArr.count > 0) {
            //轮播banner图
            _cycleScrollview.imageURLStringsGroup = _imageUrlArr;
            [[NSUserDefaults standardUserDefaults] setObject:_imageUrlArr forKey:@"bannerImageUrl"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

/*页面布局*/
- (void)createObjects{
    
    WS(ws)
    
    _stockClassTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) style:UITableViewStyleGrouped];
    _stockClassTV.backgroundColor=[UIColor clearColor];
    _stockClassTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _stockClassTV.dataSource = self;
    _stockClassTV.delegate = self;
    [_stockClassTV registerClass:[YZMyStocksTopCell class] forCellReuseIdentifier:home_page_stock_cell_identifier];
    if (!YZMSWitchOn) {
        [_stockClassTV registerNib:[UINib nibWithNibName:NSStringFromClass([YZMHomePageCell class]) bundle:nil] forCellReuseIdentifier:home_page_review_cell_identifier];
    }else{
       
    }
    [self.view addSubview:_stockClassTV];
    [_stockClassTV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(ws.view);
    }];
  
        UIView *topBgView = [[UIView  alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ceil(220*ScreenWidth/750))];
        [_stockClassTV addSubview:topBgView];
        /*Banner*/
        _cycleScrollview = [SDCycleScrollView cycleScrollViewWithFrame:topBgView.bounds delegate:self placeholderImage:[UIImage imageNamed:@"loading"]];
        _cycleScrollview.backgroundColor = [YZMAppStyle colorForLightWhite];
        _cycleScrollview.autoScrollTimeInterval = 3.0;
        if (!YZMSWitchOn) {
            _cycleScrollview.localizationImageNamesGroup = @[[UIImage imageNamed:@"banner4.png"]];
        }else{
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bannerImageUrl"]) {
                
                _cycleScrollview.imageURLStringsGroup = [[NSUserDefaults standardUserDefaults] objectForKey:@"bannerImageUrl"];
            }
        }
        [topBgView addSubview:_cycleScrollview];
        [_cycleScrollview mas_makeConstraints:^(MASConstraintMaker *make){
            
            make.edges.equalTo(topBgView);
        }];
        _stockClassTV.tableHeaderView = topBgView;
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    _refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    _refreshHeader.stateLabel.textColor = [YZMAppStyle colorForGrayText];
    _refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
    _stockClassTV.mj_header = _refreshHeader;
    
#ifdef YZMicroStock_Agent_One
    
    //T+1 T+D入口
    [self createFooterViewForAgent];
#else
    
    //T+1 T+D入口
    [self createFooterView];
#endif
    
    _imageViewRedEnvelope = [[UIImageView alloc] init];
    _imageViewRedEnvelope.image = [UIImage imageNamed:@"redenvelope"];
    NSLog(@"ScreenHeight:%f,TabBarHeight:%ld,NavigationBarHeight:%ld",ScreenHeight,TabBarHeight,TabBarHeight);
//    NSInteger tabbarH = TabBarHeight;
//    NSInteger navigationH = NavigationBarHeight;
    NSInteger originY = ScreenHeight - 86 - TabBarHeight - NavigationBarHeight;
    _imageViewRedEnvelope.frame = CGRectMake(ScreenWidth - 83 - 15, originY, 83, 86);
    [self.view addSubview:self.imageViewRedEnvelope];
    self.imageViewRedEnvelope.userInteractionEnabled = YES;
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changeFrame:)];
//    [self.imageViewRedEnvelope addGestureRecognizer:pan];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushRedPackge:)];
    [self.imageViewRedEnvelope addGestureRecognizer:tap];
}

- (void)pushRedPackge:(UITapGestureRecognizer *)tap{
    if (self.arrActivity.count == 0) {
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_enter(group);
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self fetchActivityList:group];
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [hud setHidden:YES];
            [self configRedPackageDataAndPush];
        });
        return;
    }
    [self configRedPackageDataAndPush];
    
}

- (void)configRedPackageDataAndPush{
    if (self.arrActivity.count > 0) {
        YZMActivityModel *model = self.arrActivity[0];
        NSDictionary *dic = @{@"bannerEvent":[model activityUrl], @"title":model.name, @"param":@{@"activityid":@(model.activityId)}};
        [YZMHomeBannerModel selectDirection:dic withLocal:YES];
    }
}

- (void)changeFrame:(UIPanGestureRecognizer *)recognizer{
    [recognizer.view.superview bringSubviewToFront:recognizer.view];
    
    CGPoint center = recognizer.view.center;
    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
    CGPoint translation = [recognizer translationInView:self.view];
    //NSLog(@"%@", NSStringFromCGPoint(translation));
    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        //计算速度向量的长度，当他小于200时，滑行会很短
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 1000;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866
        
        //基于速度和速度因素计算一个终点
        float slideFactor = 0.1 * slideMult;
        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
                                         center.y + (velocity.y * slideFactor));
        //限制最小［cornerRadius］和最大边界值［self.view.bounds.size.width - cornerRadius］，以免拖动出屏幕界限
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),
                           self.view.bounds.size.width - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),
                           self.view.bounds.size.height - cornerRadius - TabBarHeight);
        finalPoint.x = finalPoint.x > self.view.center.x ? [UIScreen mainScreen].bounds.size.width - recognizer.view.frame.size.width / 2.0:recognizer.view.frame.size.width / 2.0;
        
        //使用 UIView 动画使 view 滑行到终点
        [UIView animateWithDuration:0.25
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             recognizer.view.center = finalPoint;
                         }
                         completion:nil];
    }
}

- (void)createFooterView
{
    UIView *container;
    if (YZMSWitchOn) {
        UIView *bottomview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 700)];
        bottomview.backgroundColor = [UIColor clearColor];
        _stockClassTV.tableFooterView = bottomview;
        container = [self configOptionView:bottomview];
        _segView = [YZMSegmentViewScroll new];
        [bottomview addSubview:_segView];
        [_segView mas_makeConstraints:^(MASConstraintMaker *make){
            if ([[YZMBundleVersionControlService sharedService] isShowTrade]) {
                make.top.mas_equalTo(container.mas_bottom).offset(14);
            }else{
                make.top.mas_equalTo(bottomview.mas_top);
            }
            make.left.right.equalTo(bottomview);
            make.bottom.equalTo(bottomview);
        }];
         _segView.titleArray = @[@"策略榜单",@"策略动态"];
        _tradeTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) style:UITableViewStylePlain];
        _tradeTV.backgroundColor = [UIColor redColor];
        _tradeTV.delegate = self;
        _tradeTV.dataSource = self;
        _tradeTV.backgroundView = nil;
        _tradeTV.backgroundColor = [UIColor clearColor];
        _tradeTV.scrollEnabled = NO;
        _tradeTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
   
    [_tradeTV registerClass:[YZMRankCell class] forCellReuseIdentifier:home_page_trade_cell_identifier];
    
    _masterTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) style:UITableViewStylePlain];
    _masterTV.delegate = self;
    _masterTV.dataSource = self;
    _masterTV.backgroundView = nil;
    _masterTV.backgroundColor = [UIColor clearColor];
    _masterTV.scrollEnabled = NO;
    _masterTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_masterTV registerClass:[YZMTrendCell class] forCellReuseIdentifier:home_page_master_cell_identifier];
    if (YZMSWitchOn) {
        _segView.viewArray = @[_tradeTV,_masterTV];
    }
    
}

- (UIView *)configOptionView:(UIView *)bottomview{
    UIView *newView=[[UIView alloc]init];
    newView.backgroundColor=[YZMAppStyle colorForMain];
    [bottomview addSubview:newView];
    [newView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(bottomview);
        make.height.mas_equalTo(70);
    }];
    
    UIView *neWsqlitLine1 = [YZMAppStyle splitLine];
    [bottomview addSubview:neWsqlitLine1];
    
    [neWsqlitLine1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(newView.mas_bottom).offset(-1);
        make.left.equalTo(newView).offset(10);
        make.width.mas_equalTo(ScreenWidth-20);
        make.height.mas_equalTo(0.5);
    }];
    
    UIView *neWsqlitLine2 = [YZMAppStyle splitLine];
    [newView addSubview:neWsqlitLine2];
    [neWsqlitLine2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(newView);
        make.top.mas_equalTo(newView).offset(2);
        make.bottom.mas_equalTo(newView).offset(-3);
        make.width.mas_equalTo(0.5);
    }];
    
    UIView *newFirstView=[UIView new];
    [newView addSubview:newFirstView];
    [newFirstView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(newView);
        make.width.mas_equalTo(ScreenWidth/2);
    }];
    
    UILabel *newFirstRedLabel=[YZMAppStyle labelWithRedBGAndWhiteFont];
    newFirstRedLabel.text=@"新";
    [newFirstView addSubview:newFirstRedLabel];
    [newFirstRedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.top.mas_equalTo(15);
        make.width.height.mas_equalTo(20);
    }];
    
    UILabel *newfirstAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    newfirstAchoiceLabel.text=@"免费体验";
    [newFirstView addSubview:newfirstAchoiceLabel];
    [newfirstAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(newFirstRedLabel);
        make.left.equalTo(newFirstRedLabel.mas_right).offset(7);
    }];
    
    _imageViewNew = [[UIImageView alloc]init];
    _imageViewNew.image = [UIImage imageNamed:@"new2.png"];
    [newFirstView addSubview:_imageViewNew];
    [_imageViewNew mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(newfirstAchoiceLabel.mas_right).with.offset(10);
        make.top.equalTo(newFirstRedLabel.mas_top).with.offset(-8);
        make.width.equalTo(@41);
        make.height.equalTo(@18);
    }];
     BOOL isClicked =  [[NSUserDefaults standardUserDefaults] boolForKey:@"clikedFreeEx"];
    _imageViewNew.hidden = isClicked;
    UILabel *newfirstPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    newfirstPresentLabel.text=@"2000元操盘金免费领";
    [newFirstView addSubview:newfirstPresentLabel];
    [newfirstPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(newFirstRedLabel);
        make.top.equalTo(newFirstRedLabel.mas_bottom).offset(6);
    }];
    
    UIButton *newfirstButton=[UIButton buttonWithType:UIButtonTypeCustom];
    newfirstButton.backgroundColor=[UIColor clearColor];
    newfirstButton.tag=101;
    [newfirstButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [newFirstView addSubview:newfirstButton];
    [newfirstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(newFirstView);
    }];
    
    UIView *newSecondView=[[UIView alloc]init];
    [newView addSubview:newSecondView];
    [newSecondView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(newView);
        make.width.mas_equalTo(ScreenWidth/2);
    }];
    
    
    UILabel *newSecondRedLabel=[YZMAppStyle labelWithRedBGAndWhiteFont];
    newSecondRedLabel.text=@"新";
    [newSecondView addSubview:newSecondRedLabel];
    [newSecondRedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.top.mas_equalTo(15);
        make.width.height.mas_equalTo(20);
    }];
    
    UILabel *newSecondAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    newSecondAchoiceLabel.text=@"炒股大赛";
    [newSecondView addSubview:newSecondAchoiceLabel];
    [newSecondAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(newSecondRedLabel);
        make.left.equalTo(newSecondRedLabel.mas_right).offset(7);
    }];
    
    UILabel *newSecondPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    newSecondPresentLabel.text=@"万元奖金免费拿";
    [newSecondView addSubview:newSecondPresentLabel];
    [newSecondPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(newSecondRedLabel);
        make.top.equalTo(newSecondRedLabel.mas_bottom).offset(6);
    }];
    
    UIButton *newSecondButton=[UIButton buttonWithType:UIButtonTypeCustom];
    newSecondButton.backgroundColor=[UIColor clearColor];
    newSecondButton.tag=102;
    [newSecondButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [newSecondView addSubview:newSecondButton];
    [newSecondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(newSecondView);
    }];
    
    UIView *container = [[UIView alloc] init];
    container.backgroundColor = [YZMAppStyle colorForMain];
    [bottomview addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(newView);
        make.top.equalTo(newView.mas_bottom);
        make.height.mas_equalTo(70);
    }];
    
    UIView *firstView = [[UIView alloc] init];
    [container addSubview:firstView];
    [firstView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.bottom.equalTo(container);
        make.width.mas_equalTo(ScreenWidth / 2);
    }];
    
    UILabel *firstredLabel = [YZMAppStyle labelWithRedBGAndWhiteFont];
    firstredLabel.text = @"热";
    [firstView addSubview:firstredLabel];
    [firstredLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(25);
        make.top.mas_equalTo(15);
        make.width.height.mas_equalTo(20);
    }];
    
    UILabel *firstAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    firstAchoiceLabel.text=@"点买A股";
    [firstView addSubview:firstAchoiceLabel];
    [firstAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(firstredLabel);
        make.left.equalTo(firstredLabel.mas_right).offset(7);
    }];
    
    UILabel *firstWayLabel=[YZMAppStyle labelWithBuyWay];
    firstWayLabel.text = @"T+1";
    [firstView addSubview:firstWayLabel];
    [firstWayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(firstredLabel);
        make.left.equalTo(firstAchoiceLabel.mas_right).offset(6);
        make.width.mas_equalTo(38);
        make.height.mas_equalTo(16);
    }];
    
    UILabel *firstPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    firstPresentLabel.text=@"今天买 明天卖 交易灵活";
    [firstView addSubview:firstPresentLabel];
    [firstPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(firstredLabel);
        make.top.equalTo(firstredLabel.mas_bottom).offset(6);
    }];
    
    UIButton *firstButton=[UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.backgroundColor=[UIColor clearColor];
    [firstButton addTarget:self action:@selector(firstButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [firstView addSubview:firstButton];
    [firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(firstView);
    }];
    
    UIView *secondView = [[UIView alloc] init];
    [container addSubview:secondView];
    [secondView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.top.bottom.equalTo(container);
        make.width.mas_equalTo(ScreenWidth / 2);
    }];
    
    UILabel *secondPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    secondPresentLabel.text=@"耐心持股 长线必选";
    [secondView addSubview:secondPresentLabel];
    [secondPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(secondView).offset(25);
        make.centerY.equalTo(firstPresentLabel);
    }];
    
    UILabel *secondredLabel = [YZMAppStyle labelWithRedBGAndWhiteFont];
    secondredLabel.text = @"荐";
    [secondView addSubview:secondredLabel];
    [secondredLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(secondPresentLabel.mas_left);
        make.top.width.height.centerY.equalTo(firstredLabel);
    }];
    
    UILabel *secondAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    secondAchoiceLabel.text=@"点买A股";
    [secondView addSubview:secondAchoiceLabel];
    [secondAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(firstredLabel);
        make.left.equalTo(secondredLabel.mas_right).offset(7);
    }];
    
    UILabel *secondWayLabel=[YZMAppStyle labelWithBuyWay];
    secondWayLabel.text = @"T+D";
    [secondView addSubview:secondWayLabel];
    [secondWayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.width.height.equalTo(firstWayLabel);
        make.left.equalTo(secondAchoiceLabel.mas_right).offset(6);
    }];
    
    UIButton *secondButton=[UIButton buttonWithType:UIButtonTypeCustom];
    secondButton.backgroundColor=[UIColor clearColor];
    [secondButton addTarget:self action:@selector(secondButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [secondView addSubview:secondButton];
    [secondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(secondView);
    }];
    
    UIView *sqlitLine = [YZMAppStyle splitLine];
    [bottomview addSubview:sqlitLine];
    [sqlitLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(container);
        make.top.mas_equalTo(container).offset(2);
        make.bottom.mas_equalTo(container).offset(-2);
        make.width.mas_equalTo(0.5);
    }];
    return  container;
}

-(void)createFooterViewForAgent
{
    UIView *bottomview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 400)];
    bottomview.backgroundColor = [UIColor clearColor];
    _stockClassTV.tableFooterView = bottomview;
    
    UIView *newView=[[UIView alloc]init];
    newView.backgroundColor=[YZMAppStyle colorForMain];
    [bottomview addSubview:newView];
    [newView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(bottomview);
        make.height.mas_equalTo(70);
    }];
    
    UIView *neWsqlitLine1 = [YZMAppStyle splitLine];
    [bottomview addSubview:neWsqlitLine1];
    
    [neWsqlitLine1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(newView.mas_bottom).offset(-1);
        make.left.equalTo(newView).offset(10);
        make.width.mas_equalTo(ScreenWidth-20);
        make.height.mas_equalTo(0.5);
    }];
    
    UIView *neWsqlitLine2 = [YZMAppStyle splitLine];
    [newView addSubview:neWsqlitLine2];
    [neWsqlitLine2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(newView);
        make.top.mas_equalTo(newView).offset(2);
        make.bottom.mas_equalTo(newView).offset(-3);
        make.width.mas_equalTo(0.5);
    }];
    
    UIView *newFirstView=[UIView new];
    [newView addSubview:newFirstView];
    [newFirstView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(newView);
        make.width.mas_equalTo(ScreenWidth/2);
    }];
    
    UIImageView *newFirstImageView = [UIImageView new];
    [newFirstImageView setImage:[UIImage imageNamed:@"icon_for_agent_shi"]];
    [newFirstView addSubview:newFirstImageView];
    [newFirstImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(ScreenWidth*0.05);
        make.top.equalTo(newFirstView).offset(14);
        make.height.width.mas_equalTo(39);
    }];
    
 
    UILabel *newfirstAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    newfirstAchoiceLabel.text=@"一元实盘";
    [newFirstView addSubview:newfirstAchoiceLabel];
    [newfirstAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(newFirstImageView);
        make.left.equalTo(newFirstImageView.mas_right).offset(7);
    }];
    
    UIImageView *hotImageView1 = [UIImageView new];
    [hotImageView1 setImage:[UIImage imageNamed:@"icon_for_agent_hot"]];
    [newFirstView addSubview:hotImageView1];
    [hotImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(newfirstAchoiceLabel.mas_top);
        make.left.equalTo(newfirstAchoiceLabel.mas_right);
    }];
    

    UILabel *newfirstPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    newfirstPresentLabel.text=@"2000元操盘金免费领";
    [newFirstView addSubview:newfirstPresentLabel];
    [newfirstPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(newFirstImageView.mas_right);
        make.bottom.equalTo(newFirstImageView.mas_bottom);
    }];

    UIButton *newfirstButton=[UIButton buttonWithType:UIButtonTypeCustom];
    newfirstButton.backgroundColor=[UIColor clearColor];
    newfirstButton.tag=101;
    [newfirstButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [newFirstView addSubview:newfirstButton];
    [newfirstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(newFirstView);
    }];
    
    UIView *newSecondView=[[UIView alloc]init];
    [newView addSubview:newSecondView];
    [newSecondView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(newView);
        make.width.mas_equalTo(ScreenWidth/2);
    }];
    
    UIImageView *newSecondImageView = [UIImageView new];
    [newSecondImageView setImage:[UIImage imageNamed:@"icon_for_agent_simulate"]];
    [newSecondView addSubview:newSecondImageView];
    [newSecondImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(newSecondView).offset(ScreenWidth*0.05);
        make.top.equalTo(newSecondView).offset(14);
        make.height.width.mas_equalTo(39);
    }];
    

    UILabel *newSecondAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    newSecondAchoiceLabel.text=@"炒股大赛";
    [newSecondView addSubview:newSecondAchoiceLabel];
    [newSecondAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(newSecondImageView);
        make.left.equalTo(newSecondImageView.mas_right).offset(7);
    }];
    
    UIImageView *hotImageView2 = [UIImageView new];
    [hotImageView2 setImage:[UIImage imageNamed:@"icon_for_agent_hot"]];
    [newSecondView addSubview:hotImageView2];
    [hotImageView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(newSecondAchoiceLabel.mas_top);
        make.left.equalTo(newSecondAchoiceLabel.mas_right);
    }];

    UILabel *newSecondPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    newSecondPresentLabel.text=@"万元奖金免费拿";
    [newSecondView addSubview:newSecondPresentLabel];
    [newSecondPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(newSecondAchoiceLabel);
        make.bottom.equalTo(newSecondImageView);
    }];

    UIButton *newSecondButton=[UIButton buttonWithType:UIButtonTypeCustom];
    newSecondButton.backgroundColor=[UIColor clearColor];
    newSecondButton.tag=102;
    [newSecondButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [newSecondView addSubview:newSecondButton];
    [newSecondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(newSecondView);
    }];
    
    UIView *container = [[UIView alloc] init];
    container.backgroundColor = [YZMAppStyle colorForMain];
    [bottomview addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(newView);
        make.top.equalTo(newView.mas_bottom);
        make.height.mas_equalTo(70);
    }];
    
    UIView *firstView = [[UIView alloc] init];
    [container addSubview:firstView];
    [firstView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.bottom.equalTo(container);
        make.width.mas_equalTo(ScreenWidth / 2);
    }];
    
    UIImageView *FirstImageView = [UIImageView new];
    [FirstImageView setImage:[UIImage imageNamed:@"icon_a_stock"]];
    [firstView addSubview:FirstImageView];
    [FirstImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(firstView).offset(ScreenWidth*0.05);
        make.top.equalTo(firstView).offset(14);
        make.height.width.mas_equalTo(39);
    }];
    
    UILabel *firstAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    firstAchoiceLabel.text=@"T+1交易";
    [firstView addSubview:firstAchoiceLabel];
    [firstAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(FirstImageView);
        make.left.equalTo(FirstImageView.mas_right).offset(7);
    }];
    
    UIImageView *hotImageView3 = [UIImageView new];
    [hotImageView3 setImage:[UIImage imageNamed:@"icon_for_agent_hot"]];
    [firstView addSubview:hotImageView3];
    [hotImageView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(firstAchoiceLabel.mas_top);
        make.left.equalTo(firstAchoiceLabel.mas_right);
    }];
    
    UILabel *firstPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    firstPresentLabel.text=@"今买 明卖 交易灵活";
    [firstView addSubview:firstPresentLabel];
    [firstPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(FirstImageView.mas_right);
        make.bottom.equalTo(FirstImageView);
    }];
    
    UIButton *firstButton=[UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.backgroundColor=[UIColor clearColor];
    [firstButton addTarget:self action:@selector(firstButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [firstView addSubview:firstButton];
    [firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(firstView);
    }];
    
    UIView *secondView = [[UIView alloc] init];
    [container addSubview:secondView];
    [secondView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.top.bottom.equalTo(container);
        make.width.mas_equalTo(ScreenWidth / 2);
    }];
    
    
    UIImageView *SecondImageView = [UIImageView new];
    [SecondImageView setImage:[UIImage imageNamed:@"icon_for_agent_T+D"]];
    [secondView addSubview:SecondImageView];
    [SecondImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(secondView).offset(ScreenWidth*0.05);
        make.top.equalTo(secondView).offset(14);
        make.height.width.mas_equalTo(39);
    }];
    
    UILabel *secondAchoiceLabel=[YZMAppStyle labelWithMediumWhite];
    secondAchoiceLabel.text=@"T+D交易";
    [secondView addSubview:secondAchoiceLabel];
    [secondAchoiceLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(SecondImageView);
        make.left.equalTo(SecondImageView.mas_right).offset(7);
    }];
    
    UIImageView *hotImageView4 = [UIImageView new];
    [hotImageView4 setImage:[UIImage imageNamed:@"icon_for_agent_new"]];
    [secondView addSubview:hotImageView4];
    [hotImageView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(secondAchoiceLabel.mas_top);
        make.left.equalTo(secondAchoiceLabel.mas_right);
    }];
    
    UILabel *secondPresentLabel=[YZMAppStyle labelWithSmallLightGray];
    secondPresentLabel.text=@"耐心持股 长线必选";
    [secondView addSubview:secondPresentLabel];
    [secondPresentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(secondAchoiceLabel);
        make.bottom.equalTo(SecondImageView);
    }];
  
    UIButton *secondButton=[UIButton buttonWithType:UIButtonTypeCustom];
    secondButton.backgroundColor=[UIColor clearColor];
    [secondButton addTarget:self action:@selector(secondButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [secondView addSubview:secondButton];
    [secondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(secondView);
    }];
    
    UIView *sqlitLine = [YZMAppStyle splitLine];
    [bottomview addSubview:sqlitLine];
    [sqlitLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(container);
        make.top.mas_equalTo(container).offset(2);
        make.bottom.mas_equalTo(container).offset(-2);
        make.width.mas_equalTo(0.5);
    }];

    _segView = [YZMSegmentViewScroll new];
    [bottomview addSubview:_segView];
    [_segView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.top.mas_equalTo(container.mas_bottom).offset(14);
        make.left.right.equalTo(bottomview);
        make.bottom.equalTo(bottomview);
    }];
    
    _segView.titleArray = @[@"操盘达人",@"策略排行"];
    
    _tradeTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) style:UITableViewStylePlain];
    _tradeTV.delegate = self;
    _tradeTV.dataSource = self;
    _tradeTV.backgroundView = nil;
    _tradeTV.backgroundColor = [UIColor clearColor];
    _tradeTV.scrollEnabled = NO;
    _tradeTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tradeTV registerClass:[YZMTradeCell class] forCellReuseIdentifier:home_page_trade_cell_identifier];
    
    _masterTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) style:UITableViewStylePlain];
    _masterTV.delegate = self;
    _masterTV.dataSource = self;
    _masterTV.backgroundView = nil;
    _masterTV.backgroundColor = [UIColor clearColor];
    _masterTV.scrollEnabled = NO;
    _masterTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_masterTV registerClass:[YZMMasterCell class] forCellReuseIdentifier:home_page_master_cell_identifier];
    
    _segView.viewArray = @[_tradeTV,_masterTV];
    
    
}

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        
        [self endRefresh];

        if (!_unShowErrorFlag&&!_unFirstFetchAStockFlag) {
            
            [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
            _unShowErrorFlag = YES;
        }
        
        return YES;
    }
    
    return NO;
}

#pragma mark - setter and getter

- (YZMHomeOptionStockView *)optionStockView{
    if (!_optionStockView) {
        _optionStockView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMHomeOptionStockView class]) owner:self options:nil][0];
        _optionStockView.frame = CGRectMake(0, 0, YZMScreenWidth, 70);
#ifndef YZMicroStock
        _optionStockView.backgroundColor = [UIColor whiteColor];
#endif
    }
    _optionStockView.stockOneBlock = ^{
        [YZMHCMInstance pushViewControllerWithName:@"stock" andParams:nil];
    };
    
    _optionStockView.stockDBlock = ^{
        [YZMHCMInstance pushViewControllerWithName:@"stockTD" andParams:nil];
    };
    return _optionStockView;
}

- (YZMHomePageSectionView2 *)viewSection{
    if (!_viewSection) {
        _viewSection = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMHomePageSectionView2 class]) owner:self options:nil][0];
        _viewSection.deletegate = self;
    }
    return _viewSection;
}


@end
